//
//  GetBean.m
//  YanghuOnline
//
//  Created by Chengkai on 15/6/11.
//  Copyright (c) 2015年 zkingsoft. All rights reserved.
//

#import "GetBean.h"
#import <objc/message.h>

@implementation GetBean

+(id)getBean:(id)beanClass withDictionary:(NSDictionary *)dictionary{
    
//    id peopleClass = objc_getClass("BigCard");
    id result = [[beanClass alloc] init]; //创建类型的实例
    [self reflectDataFromOtherObject:dictionary withResult:result withClass:beanClass];
    return result;
}

#pragma mark 获取类型的属性名称列表
+ (NSArray*)propertyKeys:(id)classT
{
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList(classT, &outCount);
    NSMutableArray *keys = [[NSMutableArray alloc] initWithCapacity:outCount];
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        [keys addObject:propertyName];
    }
    free(properties);
    return keys;
}

#pragma mark 把NSDictionary 中的值按照属性名称设置到实体中去
+ (BOOL)reflectDataFromOtherObject:(NSObject*)dataSource withResult:(id)resultId withClass:(id)classF
{
    BOOL ret = NO;
    for (NSString *key in [self propertyKeys:classF]) {
        if ([dataSource isKindOfClass:[NSDictionary class]]) {
            ret = ([dataSource valueForKey:key]==nil)?NO:YES;
        }
        else
        {
            ret = [dataSource respondsToSelector:NSSelectorFromString(key)];
        }
        if (ret) {
            id propertyValue = [dataSource valueForKey:key];
            //该值不为NSNULL，并且也不为nil
            if (![propertyValue isKindOfClass:[NSNull class]] && propertyValue!=nil) {
                [resultId setValue:propertyValue forKey:key];
            }
        }
    }
    return ret;
}

@end
